//
//  Colum_IndexViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/31.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "Colum_IndexViewController.h"

@interface Colum_IndexViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,ASIHTTPRequestDelegate>{
    __weak IBOutlet UIScrollView *mainView;
    
    __weak IBOutlet UITableView *_tableView;
    
    __weak IBOutlet UIButton *save;
    
    NSMutableArray *textArr;//记录输入内容
    MBProgressHUD *postHud;
    NSMutableArray *indexArr;//数据arr
    NSMutableDictionary *indexDic;//数据dic
    //参数
    ASIFormDataRequest *getDataRequest;//获取数据请求
    ASIFormDataRequest *postDataRequest;//修改数据请求
    NSString *action;
    NSMutableDictionary *paramsDict;
    NSString *IdStr;
}

@end

@implementation Colum_IndexViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewDidLayoutSubviews{
    UIScreen *screen = [UIScreen mainScreen];
    mainView.frame = CGRectMake(0, 0, screen.bounds.size.width,IPHONE5 ? 469:381);
    mainView.contentSize = CGSizeMake(screen.bounds.size.width, screen.bounds.size.height - 64);
    _tableView.scrollEnabled = NO;
    _tableView.rowHeight = 50;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUI];
    textArr = [NSMutableArray array];
//    for (int j = 0; j < 10; j++) {
//        textArr[j] = @"";
//    }
    _tableView.dataSource = self;
    _tableView.delegate = self;
    save.backgroundColor = APP_COLOR;
    indexArr = [NSMutableArray array];
    [self getData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Custom Method
-(void)setUI{
    save.layer.cornerRadius = 5.0 ;
    UIScreen *screen = [UIScreen mainScreen];
    self.view.frame = CGRectMake(0, 0, screen.bounds.size.width, screen.bounds.size.height - 64 - 35);
}
- (IBAction)save:(id)sender {
    NSLog(@"%@",textArr);
    [self postData];
}

#pragma mark UITableViewDelegate Method

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"colum_index";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = (UITableViewCell *)[[NSBundle mainBundle]loadNibNamed:@"Colum_indexCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:1];
    lbl.text = [NSString stringWithFormat:@"栏目:%li",row + 1];
    UITextField *textfield = (UITextField *)[cell.contentView viewWithTag:2];
    textfield.tag = row + 10;
    textfield.delegate = self;
    textfield.text = indexDic ? indexDic[indexArr[row]] : @"";
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!indexArr || indexArr.count != 0) {
        return indexArr.count;
    }else{
        return 6;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    UITextField *text = textField;
    NSLog(@"%i",textField.tag);
    NSInteger row = text.tag - 10;
    textArr[row] = text.text;
}

#pragma mark Custom Method
-(void)getData{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在加载，请稍后...";
        }
        
        getDataRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        getDataRequest.requestMethod = @"POST";
        // 设置超时时间
        getDataRequest.timeOutSeconds = 60;
        getDataRequest.delegate = self;
        // 设置参数
        action = @"DaohangLanmumain2";
        paramsDict = [NSMutableDictionary dictionary];
        //paramsDict = @{@"uid":UNAME};//uid会员名
        [paramsDict setObject:UNAME forKey:@"uid"];
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        getDataRequest.postBody = [paramsData mutableCopy];
        
        [getDataRequest startAsynchronous];
    }
}
-(void)postData{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在修改，请稍后...";
        }
        
        postDataRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postDataRequest.requestMethod = @"POST";
        // 设置超时时间
        postDataRequest.timeOutSeconds = 60;
        postDataRequest.delegate = self;
        // 设置参数
        action = @"DaohangLanmuupdate";
        paramsDict = [NSMutableDictionary dictionary];
        
        //paramsDict = @{@"uid":UNAME,@"id":IdStr};//uid会员名
        [paramsDict setObject:UNAME forKey:@"uid"];
        [paramsDict setObject:IdStr forKey:@"id"];
        for (int i = 0; i < indexArr.count; i++) {
            //[paramsDict :textArr[i] forKey:indexArr[i]];
            [paramsDict setObject:textArr[i] forKey:indexArr[i]];
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postDataRequest.postBody = [paramsData mutableCopy];
        
        [postDataRequest startAsynchronous];
    }
}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        
        if (errorCode == 0) {
            postHud.hidden = YES;
            //[SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            if (request == getDataRequest) {
                indexDic = result[@"info"];
                [indexArr removeAllObjects];
                //textArr = [NSMutableArray array];
                [textArr removeAllObjects];
                NSArray *KeysArr = indexDic.allKeys;
                for (int i = 0; i < indexDic.allKeys.count; i++) {
                    if ([KeysArr[i] isEqualToString:@"ID"]) {
                        IdStr = indexDic[@"ID"];
                        continue;
                    }
                    [indexArr addObject:KeysArr[i]];
                }
                //排序
                [indexArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                    NSString *str1 = [obj1 substringFromIndex:5];
                    NSString *str2 = [obj2 substringFromIndex:5];
                    if ([str1 intValue] > [str2 intValue]){
                        return NSOrderedDescending;
                    }
                    if ([str1 intValue] < [str2 intValue]){
                        return NSOrderedAscending;
                    }
                    return NSOrderedSame;
                }];
                for (int i = 0; i < indexArr.count; i++) {
                    [textArr addObject:indexDic[indexArr[i]]];
                }
                [_tableView reloadData];//更新数据
            }else{
                [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            }
        }
        
    } else {
        postHud.hidden = YES;
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


-(void)dealloc{
    
    [getDataRequest cancel];
    [postDataRequest cancel];
    postHud = nil;
    getDataRequest = nil;
    postDataRequest = nil;
    
}
//刷新数据
-(void)reFreshData{
    [self getData];
}

@end
